<template>
  <div class="authority">
    <div class="gva-table-box unit">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="addUnit">新增用户</el-button>
      </div>
      <el-table :data="tableData" row-key="id">
        <el-table-column align="left" label="头像">
          <template #default="scope">
            <img v-if="scope.row.headerImg" :src="scope.row.headerImg" style="width: 50px;height:50px;border-radius: 50%;">
            <img v-else src="@/assets/noBody.png" style="width: 50px;height:50px;border-radius: 50%;">
          </template>
        </el-table-column>
        <el-table-column align="left" label="姓名" prop="name"></el-table-column>
        <el-table-column align="left" label="账号" prop="username" show-overflow-tooltip></el-table-column>
        <el-table-column align="left" fixed="right" label="操作" min-width="160">
          <template #default="scope">
            <el-button type="primary" link icon="edit" @click="editUnit(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link icon="delete" @click="delUnit(scope.row)">
              删除
            </el-button>
            <el-button type="primary" link icon="edit" @click="updatePassword(scope.row)">
              修改密码
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination v-model:current-page="page" :page-size="pageSize" :total="total" layout="prev, pager, next"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <el-drawer v-model="dialogFormVisible" :size="appStore.drawerSize" :before-close="handleClose" :show-close="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{ dialogTitle }}</span>
          <div>
            <el-button @click="closeDialog"> 取 消 </el-button>
            <el-button type="primary" @click="enterDialog"> 确 定 </el-button>
          </div>
        </div>
      </template>
      <el-form v-if="dialogFormVisible" ref="userForm" label-width="100" :model="form" :rules="rules">
        <el-row class="w-full">
          <el-col :span="12">
            <el-form-item label="账号" prop="username">
              <el-input v-model="form.username" placeholder="请输入"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" v-if="isEdit">
              <el-input v-model="form.password" disabled />
            </el-form-item>
            <el-form-item label="密码" prop="password" v-else>
              <el-input v-model="form.password" placeholder="请输入"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="w-full">
          <el-col :span="12">
            <el-form-item label="角色" prop="roleId">
              <el-select v-model="form.roleId" placeholder="请选择" style="width: 100%">
                <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名">
              <el-input v-model="form.name" placeholder="请输入"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="w-full">
          <el-col :span="12">
            <el-form-item label="联系方式">
              <el-input v-model="form.mobile" placeholder="请输入"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="w-full">
          <!-- <el-col :span="12">
            <el-form-item label="组织">
              <el-cascader style="width: 100%;" :options="departList" :props="props1" clearable v-model="pids" />
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row class="w-full">
          <el-col :span="12">
            <el-form-item label="头像">
              <el-upload v-model:file-list="fileList" :action="adminUrl" :on-success="uploadSuccess"
                :headers="headerOdj" list-type="picture-card">
                <el-icon>
                  <Plus />
                </el-icon>
                <template #file="{ file }">
                  <div>
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                    <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                        <el-icon>
                          <Delete />
                        </el-icon>
                      </span>
                    </span>
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-drawer>
    <el-drawer v-model="dialogFormVisible2" :size="appStore.drawerSize" :before-close="handleClose2"
      :show-close="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">修改密码</span>
          <div>
            <el-button @click="closeDialog2"> 取 消 </el-button>
            <el-button type="primary" @click="enterDialog2"> 确 定 </el-button>
          </div>
        </div>
      </template>
      <el-form ref="passwordForm" v-if="dialogFormVisible2" label-width="100" :model="form2" :rules="rules2">
        <el-row class="w-full">
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form2.password" placeholder="请输入"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-drawer>
  </div>
</template>
<script setup>
import {
  getAuthorityList
} from '@/api/authority'
import {
  getUserList,
  deleteUser,
  createUser,
  editUser,
  modifyPassword
} from '@/api/user'

import { useUserStore } from '@/pinia/modules/user'
import { reactive, ref, onMounted } from 'vue'
import { useAppStore } from "@/pinia";
import { ElMessage, ElMessageBox } from 'element-plus'
import CustomPic from '@/components/customPic/index.vue'
defineOptions({
  name: 'User'
})
const appStore = useAppStore()
const defaultProps = {
  children: 'children',
  label: 'name',
}

const userStore = useUserStore()

const headerOdj = ref({ token: userStore.token })
const adminUrl = ref('')
adminUrl.value = import.meta.env.VITE_BASE_PATH + '/file/upload'

const form = ref({
  username: '',
  password: '',
  name: '',
  mobile: '',
  roleId: '',
  unitId: '',
  headerImg: ''
})
const rules2 = reactive({
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
})
const rules = reactive({
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  roleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
  unitId: [{ required: true, message: '请选择单位', trigger: 'change' }]
})
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const dialogFormVisible = ref(false)
const dialogFormVisible2 = ref(false)
const userForm = ref(null)
const pids = ref([])
const props1 = {
  label: 'name',
  value: 'id'
}
const initForm = () => {
  userForm.value.resetFields()
  form.value = {
    username: '',
    password: '',
    name: '',
    mobile: '',
    roleId: '',
    unitId: '',
    headerImg: ''
  }
  fileList.value = []
  pids.value = []
}
const isEdit = ref(false)
const dialogTitle = ref('新增用户')
const addUnit = () => {
  dialogTitle.value = '新增用户'
  isEdit.value = false
  dialogFormVisible.value = true
}
const closeDialog = () => {
  initForm()
  dialogFormVisible.value = false
}
const handleClose = (done) => {
  initForm()
  done()
}

const handleClose2 = (done) => {
  dialogFormVisible2.value = false
  form2.value = {
    password: '',
    userId: ''
  }
}
const closeDialog2 = () => {
  form2.value = {
    password: '',
    userId: ''
  }
  dialogFormVisible2.value = false
}
const tableData = ref([])
// 查询
const getTableData = async () => {
  const res = await getUserList({
    pageNumber: page.value,
    pageSize: pageSize.value
  })
  if (res.code == 200) {
    tableData.value = res.result.data
    total.value = res.result.total
  }
}
getTableData()

const roleList = ref([])
const unitList = ref([])
const departList = ref([])
onMounted(() => {
  getAuthorityList().then(res => {
    roleList.value = res.result
  })
})

const enterDialog = async () => {
  userForm.value.validate(async (valid) => {
    if (valid) {
      form.value.departId = pids.value.length > 0 ? pids.value[pids.value.length - 1] : form.value.departId
      let res
      if (isEdit.value) {
        res = await editUser(form.value)
      } else {
        res = await createUser(form.value)
      }
      if (res.code == 200) {
        ElMessage({
          type: 'success',
          message: isEdit.value ? '编辑成功' : '添加成功!'
        })
        getTableData()
      }
      initForm()
      dialogFormVisible.value = false
    }
  })
}
const delUnit = (row) => {
  ElMessageBox.confirm(
    '确认删除?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const res = await deleteUser(row.id)
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      getTableData()
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}
const handleCurrentChange = (val) => {
    page.value = val
    getTableData()
}
const editUnit = async (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑用户'
  pids.value = getPids(row)
  form.value = JSON.parse(JSON.stringify(row))
  form.value.userId = form.value.id
  if (form.value.personalSignature) {
    fileList.value = [{
      name: '1',
      url: form.value.personalSignature
    }]
  }
  dialogFormVisible.value = true
}
const getPids = (row) => {
  let res = []
  departList.value.forEach(item => {
    if (item.id == row.id) {
      res.push(item.id)
    }
    if (item.children.length > 0) {
      item.children.forEach(m => {
        if (m.id == row.id) {
          res.push(item.id)
          res.push(m.id)
        }
        if (m.children.length > 0) {
          m.children.forEach(n => {
            if (n.id == row.id) {
              res.push(item.id)
              res.push(m.id)
              res.push(n.id)
            }
          })
        }
      })
    }
  })
  return res
}
const form2 = ref({
  password: '',
  userId: ''
})
const updatePassword = (row) => {
  dialogFormVisible2.value = true
  form2.value.userId = row.id
}
const passwordForm = ref(null)
const enterDialog2 = async () => {
  passwordForm.value.validate(async (valid) => {
    if (valid) {
      let res = await modifyPassword(form2.value)
      if (res.code == 200) {
        ElMessage({
          type: 'success',
          message: '修改成功'
        })
      }
      form2.value = {
        password: '',
        userId: ''
      }
      dialogFormVisible2.value = false
    }
  })
}
const fileList = ref([])
const handleRemove = (file) => {
  fileList.value = []
  form.value.headerImg = ''
}
const uploadSuccess = (res) => {
  if (res.code != 200) {
    ElMessage({
      type: 'warning',
      message: res.message
    })
    fileList.value.pop()
    return
  }
  form.value.headerImg = res.result
}
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

const handleDownload = (file) => {

}
function unitChange(val){
    form.value.unitId= val[val.length-1]
}
</script>

<style lang="scss">
.el-upload-list--picture-card {
  display: flex;
  flex-wrap: nowrap;
}
.el-upload-list__item{
  justify-content: center;
}
</style>
